package com.nervenets.web.controller.handler.user.wealth;

import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.AuthStatus;
import com.nervenets.web.hibernate.domain.user.Bank;

import javax.servlet.http.HttpServletRequest;

public class UserBankEditHandler extends Handler<UserBankEditParams> {
    @Override
    public String handle(UserBankEditParams params, HttpServletRequest request) throws Exception {
        Bank bank = new Bank();
        if (params.getBankId() > 0) {
            bank = userDao.findById(params.getBankId(), Bank.class);
            if (null == bank) return errorMessage(MessageCode.code_404, "您修改的银行账号不存在");
            if (!params.getNumber().equals(bank.getNumber())) {
                Bank numberByBank = userDao.getBank(params.getUserId(), params.getNumber());
                if (null != numberByBank) return errorMessage(MessageCode.code_444, "该银行卡号已使用");
            }
        }

        if (bank.isNew()) {
            Bank numberByBank = userDao.getBank(params.getUserId(), params.getNumber());
            if (null != numberByBank) return errorMessage(MessageCode.code_444, "该银行卡号已添加");
        }

        bank.setUserId(params.getUserId());
        bank.setTagId(params.getTagId());
        bank.setName(params.getName());
        bank.setNumber(params.getNumber());
        bank.setBankAddress(params.getBankAddress());
        bank.setAuthStatus(AuthStatus.checking);
        userDao.saveOrUpdate(bank);
        return successMessage(bank);
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
